package magicloan.auctionpocket.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.immortalviewpager.AutoScrollViewPager;
import com.immortalviewpager.FillingViewsListener;
import com.utils.module.ImgRequestLayout;
import com.utils.module.ScreenUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import magicloan.auctionpocket.R;
import magicloan.auctionpocket.bean.ProduceBean;
import magicloan.auctionpocket.ui.activity.ProductDetailActivity;
import magicloan.auctionpocket.view.VerticalTextViewHelper;

/**
 * Created by hechao on 2018/1/26.
 * https://www.jianshu.com/p/f792cc343f6f
 */
public class ReFirstFragmentAdapter extends RecyclerView.Adapter {

    public static final int TYPE_HEADER = 0;
    public static final int TYPE_NORMAL = 1;

    private ArrayList<ProduceBean> mArrayList;
    private ArrayList<ProduceBean> headerMArrayList;
    private ArrayList mVerticalList;
    private Context mContext;
    private Activity mActivity;
    private MainFgGvLoanAdapter mGvAdapter;
    private VerticalTextViewHelper mVerticalTvHelper;
    private ImmorVpAdapterMainFg mTopVpAdapter;
    private JSONArray mTopUrlArray;
    public RecyclerView mRecyclerView;
    private String arr = "[{\"reminder\":\"\",\"rateType\":1,\"obtainTime\":\"10分钟\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"20-45周岁\",\"show\":1,\"type\":0,\"loanScopeEnd\":20000,\"urlType\":0,\"id\":240,\"rank\":1,\"rate\":\"0.9\",\"description\":\"全自动审核放款，20000元即时到账\",\"loanScopeStart\":1000,\"loanPeriodScopeGrads\":\"1,2,4,6,8,10,12\",\"key\":\"banner_1511175294767\",\"loanPeriodScope\":\"1-12个月\",\"clearForm\":0,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1491388278455.png\",\"loanScopeGrads\":\"1000,2000,5000,10000,15000,20000\",\"url0\":\"\",\"labels\":\"申请流程快(109),手续简单(177),快速审核(91),下款神速(71),利率合适(125),额度满意(134)\",\"starPoints\":50,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/\",\"codeType\":1,\"code\":\"var hm=document.createElement('script');hm.src='https:\\/\\/file.cainiaodk.com\\/banner_1509157584295.js?t=1515737928493';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(hm, s);var hm=document.createElement('script');hm.src='https:\\/\\/file.cainiaodk.com\\/ajaxhook.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(hm, s);\",\"url\":\"http:\\/\\/m.haomoney.com\\/activity\\/reg\\/register.html?utm_source=wap_cainiaodaikuan3\",\"sign\":\"1\",\"needDatum\":\"身份证\",\"commentNum\":128,\"applyNum\":453789,\"labels1\":\"额度小,审核时间长,利息贵,放款慢,联系不到客服,看征信\",\"labels0\":\"申请流程快,手续简单,快速审核,下款神速,利率合适,额度满意\",\"loanScope\":\"1000-20000\",\"tittle\":\"小树时代\",\"explain\":\"1、无抵押、无担保，纯信用贷款； \\n2、全自动审核放款，即时到账；\\n3、按天计息，一次审核，循环提现，定期提额；\\n4、支持部分还款，容时还款，提前还款，不需支付额外费用\",\"productName\":\"\",\"channel\":\"\",\"handler\":{}},{\"reminder\":\"1\",\"rateType\":0,\"obtainTime\":\"10分钟\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"1\",\"show\":1,\"type\":0,\"loanScopeEnd\":5000,\"urlType\":1,\"id\":182,\"rank\":2,\"rate\":\"1\",\"description\":\"1\",\"loanScopeStart\":3000,\"loanPeriodScopeGrads\":\"1\",\"key\":\"banner_1502426806666\",\"loanPeriodScope\":\"6-12个月\",\"clearForm\":0,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1508911852214.png\",\"loanScopeGrads\":\"1\",\"url0\":\"\",\"labels\":\"1\",\"starPoints\":1,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/1505980935312.png\",\"codeType\":1,\"code\":\"\",\"url\":\"http:\\/\\/m.haomoney.com\\/activity\\/reg\\/register.html?utm_source=wap_cainiaodaikuan\",\"sign\":\"1\",\"needDatum\":\"1\",\"commentNum\":4,\"applyNum\":1,\"labels1\":\"1\",\"labels0\":\"1\",\"loanScope\":\"3000-5000\",\"tittle\":\"天神贷\",\"explain\":\"1\",\"productName\":\"天神贷\",\"channel\":\"\",\"handler\":{}},{\"reminder\":\"1\",\"rateType\":0,\"obtainTime\":\"1\",\"client\":\"所有\",\"dateTime\":null,\"applyCondition\":\"1\",\"show\":1,\"type\":0,\"loanScopeEnd\":0,\"urlType\":0,\"id\":110,\"rank\":3,\"rate\":\"1\",\"description\":\"1\",\"loanScopeStart\":0,\"loanPeriodScopeGrads\":\"1\",\"key\":\"banner_8ee039\",\"loanPeriodScope\":\"6-12个月\",\"clearForm\":1,\"icon\":\"https:\\/\\/icon.cainiaodk.com\\/1502943433196.png\",\"loanScopeGrads\":\"1\",\"url0\":\"\",\"labels\":\"1\",\"starPoints\":0,\"image\":\"https:\\/\\/icon.cainiaodk.com\\/1504496036288.png\",\"codeType\":1,\"code\":\"\",\"url\":\"http:\\/\\/wap.apass.vcash.cn\\/#\\/downAppReg?channel=cndk\",\"sign\":\"1\",\"needDatum\":\"1\",\"commentNum\":5,\"applyNum\":1,\"labels1\":\"1\",\"labels0\":\"1\",\"loanScope\":\"1000-20000\",\"tittle\":\"安家趣花\",\"explain\":\"1\",\"productName\":\"安家趣花\",\"channel\":\"\",\"handler\":{}}]";

    public <T> ReFirstFragmentAdapter(final Activity activity, ArrayList<ProduceBean> reDateList, ArrayList mHeaderReDateList) {
        super();
        mActivity = activity;
        mContext = activity;
        mArrayList = reDateList;
        headerMArrayList = mHeaderReDateList;
        mGvAdapter = new MainFgGvLoanAdapter(activity);
        mVerticalTvHelper = new VerticalTextViewHelper(mActivity);
        mTopVpAdapter = new ImmorVpAdapterMainFg(mContext);

        mVerticalList = new ArrayList();
        mVerticalList.add("哈哈哈哈哈哈 你好啊 ");
        mVerticalList.add("1234567891 你好啊 ");
        mVerticalList.add("oooooooooo 你好啊 ");

        // 开始倒计时计数
        startLastTimeCount(activity);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (TYPE_NORMAL == viewType) {
            View nView = View.inflate(mContext, R.layout.fg_first_re_item, null);
            return new MyViewHolder(nView);
        } else if (TYPE_HEADER == viewType) {
            View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.fg_first_re_headv, parent, false);
            return new MyViewHolder_HeadView(layout);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder_HeadView) {
            setHeadViewData((MyViewHolder_HeadView) holder);
        } else {
            MyViewHolder myVIewHolder = (MyViewHolder) holder;
            if (position < 0 || position >= mArrayList.size())
                return;
            myVIewHolder.tv_my_count_time.setText("00:0" + position + ":" + mArrayList.get(position).hasTime);
            myVIewHolder.mRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, ProductDetailActivity.class);
                    mActivity.startActivity(intent);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
//        if ( mHeadViewRes != -1 )
        return mArrayList == null ? 0 : mArrayList.size() + 1;
//        else
//            return mArrayList == null ? 0 : mArrayList.size();
    }

    @Override
    public int getItemViewType(int position) {
//        if ( mHeadViewRes == -1 )
//            return TYPE_NORMAL;
//        else if ( mHeadViewRes != -1 && position == 0)
//            return TYPE_HEADER;
//        else
//            return TYPE_NORMAL;
        if (position == 0)
            return TYPE_HEADER;
        else
            return TYPE_NORMAL;
    }

    private class MyViewHolder extends RecyclerView.ViewHolder {

        public View mRoot;
        public TextView tv_my_count_time;

        public MyViewHolder(View itemView) {
            super(itemView);
            mRoot = itemView.findViewById(R.id.root);
            tv_my_count_time = (TextView) itemView.findViewById(R.id.tv_my_count_time);
            itemView.setTag(this);
        }

    }

    private class MyViewHolder_HeadView extends RecyclerView.ViewHolder {

        private GridView mGridView;
        private TextSwitcher mTextSwitcher;
        private AutoScrollViewPager vp_top_mainfg;
        private LinearLayout ll_top_container;
        private RelativeLayout rl;

        public MyViewHolder_HeadView(View itemView) {
            super(itemView);
            mGridView = (GridView) itemView.findViewById(R.id.gv_identify_mainfg);
            mTextSwitcher = (TextSwitcher) itemView.findViewById(R.id.textSwitcher1);
            //顶部VP
            vp_top_mainfg = (AutoScrollViewPager) itemView.findViewById(R.id.vp_top_mainfg);
            ll_top_container = (LinearLayout) itemView.findViewById(R.id.ll_top_container);
            rl = (RelativeLayout) itemView.findViewById(R.id.rl);
        }
    }


    //------------HeadView 逻辑
    private void setHeadViewData(final MyViewHolder_HeadView viewHolder) {

        // GridView
        if (headerMArrayList != null && headerMArrayList.size() > 0) {
            viewHolder.mGridView.setAdapter(mGvAdapter);
            mGvAdapter.setDatas(headerMArrayList);
            mGvAdapter.notifyDataSetChanged();
        }

        //垂直滚动LV
        if (mVerticalList != null && mVerticalList.size() > 0) {
            mVerticalTvHelper.setData(mVerticalList);
            mVerticalTvHelper.initSwitcher(viewHolder.mTextSwitcher, new VerticalTextViewHelper.OnSwitchTvClickListener() {
                @Override
                public void onClick(int position) {

                }
            });
        }

        //顶部ViewPager
        try {
            mTopUrlArray = new JSONArray(arr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mTopUrlArray != null && mTopUrlArray.length() > 0) {
            viewHolder.vp_top_mainfg.setAdapter(mTopVpAdapter);
            mTopVpAdapter.setBtmCount(viewHolder.ll_top_container,
                    R.layout.single_circleimg, mTopUrlArray.length(), R.mipmap.vp_choose,
                    R.mipmap.vp_unchoose, ScreenUtils.getScreenHeight(mContext) / 100);
            mTopVpAdapter.initViewList(mTopUrlArray.length(), R.layout.vp_item_banner_mainfg,//topUrlArray.length()
                    new FillingViewsListener() {

                        @Override
                        public void fillingView(View view, int position) {
                            final JSONObject obj = mTopUrlArray.optJSONObject(position);
                            ImageView img = (ImageView) view.findViewById(R.id.auto_vp_img);
                            ImgRequestLayout.requestLayout(viewHolder.rl, mContext, 161.0f, 375.0f);
                            Glide.with(mContext)
                                    .load(obj.optString("image"))
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(img);
                        }

                    });
            mTopVpAdapter.notifyDataSetChanged();
            viewHolder.vp_top_mainfg.setCurrentItem(1);
            viewHolder.vp_top_mainfg.setInterval(2500);
            viewHolder.vp_top_mainfg.startAutoScroll();
        }
    }

    /**
     * 开始倒计时计数
     *
     * @param activity
     */
    private void startLastTimeCount(final Activity activity) {
        // 轮询条目倒计时
        new Thread() {
            @Override
            public void run() {
                while (!activity.isFinishing()) {
                    try {
                        if (mArrayList != null) {
                            for (int i = 0; i < mArrayList.size(); i++) {
                                mArrayList.get(i).hasTime = mArrayList.get(i).hasTime - 1;
                                if (mArrayList.get(i).hasTime < 0) {  // TODO 假数据倒计时轮询
                                    mArrayList.get(i).hasTime = 10 + i * 2;
                                }
                            }
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRecyclerView != null) {
                                        for (int i = 0; i < mRecyclerView.getChildCount(); i++) {
                                            Object tag = mRecyclerView.getChildAt(i).getTag();
                                            if (tag != null && tag instanceof MyViewHolder) {
                                                GridLayoutManager layoutManager = (GridLayoutManager) mRecyclerView.getLayoutManager();
                                                if (layoutManager == null)
                                                    return;
                                                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                                                int dataIndex = (i + firstVisibleItemPosition - 1);
                                                Log.i("adapter_index_debug", "i：" + i + "==================" + "firstVisible：" + firstVisibleItemPosition);
                                                if (dataIndex < 0 || dataIndex >= mArrayList.size())
                                                    return;
                                                MyViewHolder viewHolder = (MyViewHolder) tag;
                                                viewHolder.tv_my_count_time.setText("00:0" + dataIndex + ":" + mArrayList.get(dataIndex).hasTime);
                                            }
                                        }
                                    }
                                }
                            });
                        }
                        // 随着竞拍列表越来越长，遍历一次的时间也会长，剪短休息时间
                        long sleepTime = 1000 - 1 * (mArrayList.size() / 10);
                        if (sleepTime < 500)
                            sleepTime = 500;
                        sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}
